package com.lj.frame.file.controller;


import com.lj.commons.exception.YerException;
import com.lj.commons.reponse.Result;
import com.lj.frame.file.entity.FileConf;
import com.lj.frame.file.repo.FileConfRepository;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
@Slf4j
@RequestMapping("file-conf")
@RestController
public class FileConfController {

    private final FileConfRepository fileConfRepository;


    @ApiOperation(value = "文件存储列表")
    @GetMapping("list")
    public Result getList(){
        List<FileConf> fileConfList =  fileConfRepository.list();
        return Result.ok(fileConfList);
    }

    @ApiOperation(value = "保存文件存储")
    @GetMapping("save")
    public Result save(@RequestBody FileConf fileConf){
        FileConf has = fileConfRepository.getById(fileConf.getType());
        if (Objects.nonNull(has)){
            fileConfRepository.updateById(fileConf);
        }else{
            fileConfRepository.save(fileConf);
        }
        return Result.ok();
    }


    @ApiOperation(value = "激活文件存储")
    @PostMapping("active/{type}")
    public Result active(@PathVariable("type")String type) throws YerException {
        if (null == fileConfRepository.getById(type)){
            throw new YerException("没有相关配置");
        }
        fileConfRepository.lambdaUpdate().set(FileConf::getIsActive, false).update();
        fileConfRepository.lambdaUpdate().eq(FileConf::getType, type).set(FileConf::getIsActive, true).update();
        return Result.ok();
    }
}
